﻿using JESAI.DistributedLock.Internal;
using JESAI.DistributedLock.Redis.RedLock;
using System.Threading;
using System.Threading.Tasks;

namespace JESAI.DistributedLock.Redis;

/// <summary>
/// 为 <see cref="RedisDistributedReaderWriterLock"/> 实现 <see cref="IDistributedSynchronizationHandle"/> 接口。
/// 该类用于管理分布式读写锁的句柄，提供了获取锁丢失通知的令牌、同步和异步释放锁的方法。
/// </summary>
public sealed class RedisDistributedReaderWriterLockHandle : IDistributedSynchronizationHandle
{
    private RedLockHandle? _innerHandle;

    internal RedisDistributedReaderWriterLockHandle(RedLockHandle innerHandle)
    {
        this._innerHandle = innerHandle;
    }

    /// <summary>
    /// 实现 <see cref="IDistributedSynchronizationHandle.HandleLostToken"/> 接口。
    /// 返回一个 <see cref="CancellationToken"/>，用于通知锁丢失的情况。
    /// </summary>
    public CancellationToken HandleLostToken => Volatile.Read(ref this._innerHandle)?.HandleLostToken ?? throw this.ObjectDisposed();

    /// <summary>
    /// 释放锁。
    /// </summary>
    public void Dispose() => Interlocked.Exchange(ref this._innerHandle, null)?.Dispose();

    /// <summary>
    /// 异步释放锁。
    /// </summary>
    /// <returns>一个 <see cref="ValueTask"/>，表示异步操作的结果。</returns>
    public ValueTask DisposeAsync() => Interlocked.Exchange(ref this._innerHandle, null)?.DisposeAsync() ?? default;
}
